
#include "stdafx.h"
#include "SimThread.h"
#include <process.h>

CSimThread::CSimThread(void)
{
	m_cThreadInfo.nState=STATE_IDLE;
}

CSimThread::~CSimThread(void)
{
	StopThread();
}

bool CSimThread::StartThread()
{
	m_cThreadInfo.pThis=(void*)this;
	m_cThreadInfo.nState=STATE_WORK;
	UINT nThreadId;
	m_cThreadInfo.hThread=(HANDLE)_beginthreadex(NULL,0,WorkThread,(void*)&m_cThreadInfo,0,&nThreadId);

	if(m_cThreadInfo.hThread!=NULL)
	{
		Sleep(100);
		return true;
	}
	else
	{
		m_cThreadInfo.nState=STATE_IDLE;
		return false;
	}
}

void CSimThread::StopThread()
{
	if(m_cThreadInfo.nState==STATE_IDLE)
		return;

	m_cThreadInfo.nState=STATE_READY;
	while(m_cThreadInfo.nState!=STATE_IDLE)
		Sleep(100);
}

bool CSimThread::IsStart()
{
	return (m_cThreadInfo.nState!=STATE_IDLE);
}

bool CSimThread::WorkInit()
{
	return true;
}

static UINT WINAPI WorkThread(LPVOID p)
{
	ThreadInfo *pInfo=(ThreadInfo*)p;
	CSimThread *pThis=(CSimThread*)pInfo->pThis;

	if(pThis->WorkInit()) 
	{
		while(pInfo->nState==STATE_WORK)
		{
			if(!pThis->WorkProc())
				break;
		}
		pThis->WorkUninit();
	}

	CloseHandle(pInfo->hThread);
	pInfo->hThread=NULL;
	pInfo->nState=STATE_IDLE;
	return 0;
}

void CSimThread::WorkUninit()
{
}
